import { fromCallback, checkError } from '../../universalify'
import fs from '../fs'
import path from '../../node/path'
import mkdir from '../mkdirs'
import pathExists from '../path-exists'

function outputFile (file, data, encoding?, callback?) {
    if (typeof encoding === 'function') {
        callback = encoding
        encoding = { encoding: 'utf-8' }
    }

    const dir = path.dirname(file)
    pathExists.pathExists(dir, (err, itDoes) => {
        if (checkError(err)) return callback(err)
        if (itDoes) return fs.writeFile(file, data, encoding, callback)

        mkdir.mkdirs(dir, err => {
            if (checkError(err)) return callback(err)

            fs.writeFile(file, data, encoding, callback)
        })
    })
}

function outputFileSync (file, data, options?) {
    const dir = path.dirname(file)
    if (pathExists.pathExistsSync(dir)) {
        return fs.writeFileSync(file, data, options)
    }
    mkdir.mkdirsSync(dir)
    fs.writeFileSync(file, data, options)
}

export default {
    outputFile: fromCallback(outputFile),
    outputFileSync
}
